package com.zz.yt.test.delegate.net.up;

import android.content.Context;
import android.view.View;

import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.ViewUtils;
import com.whf.android.jar.net.RestClient;
import com.whf.android.jar.net.callback.IRequest;
import com.whf.android.jar.popup.listener.OnClickDecisionListener;
import com.whf.android.jar.util.log.LatteLogger;

import org.jetbrains.annotations.NotNull;


/**
 * 升级版本
 *
 * @author qf
 * @version 22.3.12
 */
public class UpVersionUtils implements OnClickDecisionListener {

    private final UpVersionPopup mComplexPopup;
    private View.OnClickListener mClickListener = null;

    private UpVersionUtils(Context context) {
        this.mComplexPopup = UpVersionPopup.create(context);
        this.mComplexPopup.setOnClickListener(this);
    }

    @NotNull
    public static UpVersionUtils create(Context context) {
        return new UpVersionUtils(context);
    }

    public UpVersionUtils setOnClickListener(View.OnClickListener listener) {
        this.mClickListener = listener;
        return this;
    }

    public void show() {
        mComplexPopup.start();
    }


    @Override
    public void onConfirm(Object decision) {
        RestClient.builder()
                .url("http://218.28.143.172:8090/apk/YDBG.apk")
                .name("YDBG.apk")
                .extension("apk")
                .failure(this::dismiss)
                .error((code, msg) -> {
                    dismiss();
                    LatteLogger.e(msg == null ? "下载失败，请稍后再试。" : msg);
                    ToastUtils.showShort(msg == null ? "下载失败，请稍后再试。" : msg);
                })
                .onRequest(new IRequest() {
                    @Override
                    public void onRequestStart() {

                    }

                    @Override
                    public void onRequestProgress(int progress) {
                        ViewUtils.runOnUiThread(() -> setProgressBar(progress));
                    }

                    @Override
                    public void onRequestEnd() {
                        dismiss();
                        if (mClickListener != null) {
                            mClickListener.onClick(null);
                        }
                    }
                })
                .build()
                .download();
    }


    @Override
    public void onCancel() {
        if (mClickListener != null) {
            mClickListener.onClick(null);
        }
    }

    private void setProgressBar(int progress) {
        if (mComplexPopup != null) {
            mComplexPopup.setProgressBar(progress);
        }
    }

    private void dismiss() {
        if (mComplexPopup != null) {
            mComplexPopup.dismiss();
        }
    }

}
